package com.zhz.mall.portal.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhz.mall.common.api.CommonResult;
import com.zhz.mall.portal.dto.ConfirmOrderDTO;
import com.zhz.mall.portal.dto.OrderDetailDTO;
import com.zhz.mall.portal.dto.OrderListDTO;
import com.zhz.mall.portal.dto.OrderParamDTO;
import com.zhz.mall.portal.modules.oms.model.OmsOrder;
import com.zhz.mall.portal.modules.oms.service.OmsOrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/***
 * @Author zhouhengzhe
 */
@RestController
@Api("订单服务接口")
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OmsOrderService orderService;

    /**
     * 加入购物车---生成确认订单实现
     * 立即购买—生成确认订单实现 product_id  sku_id. 改成DTO接收
     * 复用业务逻辑的代码 product_id 和sku_id 查出购物车对象所需要信息
     * 初始化确认订单的商品和收货地址信息
     * this.axios.post('/order/generateConfirmOrder',Qs.stringify({itemIds: constStore.itemids}
     */
    @PostMapping("generateConfirmOrder")
    public CommonResult<ConfirmOrderDTO> generateConfirmOrder(@RequestParam("itemIds") List<Long> ids) {
        return CommonResult.success(orderService.generateConfirmOrder(ids));
    }

    /**
     * 生成订单(下单）
     * this.axios
     * .post("/order/generateOrder", {
     */
    @PostMapping("/generateOrder")
    public CommonResult<Long> generateOrder(@RequestBody OrderParamDTO paramDTO) {
        OmsOrder omsOrder = orderService.generateOrder(paramDTO);
        return CommonResult.success(omsOrder.getId());
    }

    /**
     * 读取下单成功后的订单详情
     * this.axios.get(`/order/orderDetail?orderId=${this.orderId}`).then((res)=>{
     */
    @GetMapping(value = "/orderDetail")
    public CommonResult<OrderDetailDTO> getOrderDetail(@RequestParam("orderId") Long id) {
        return CommonResult.success(orderService.getOrderDetail(id));
    }

    /**
     * 我的订单列表
     * this.axios.post('/order/list/userOrder',Qs.stringify({
     * pageSize:10,
     * pageNum:this.pageNum
     */
    @PostMapping("/list/userOrder")
    public CommonResult<IPage<OrderListDTO>> getMyOrders(
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        return CommonResult.success(orderService.getMyOrders(pageSize, pageNum));
    }


    @PostMapping("/paySuccess/{payType}")
    public void getMyOrders(
            @PathVariable("payType") Integer payType,
            HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            if (!name.toLowerCase().equals("sign_type")) {
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "" ;
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + "," ;
                }
                //乱码解决，这段代码在出现乱码时使用
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
        }

        String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwUpyecFNQ+yaW2jWzQA71LEcT1xk62vOpNukZFOWCDTKxL2WY6OVv4uh2RajKFdslHfWjvwooXr5TsKtvnv0iRLDjbsuh6H6va5jWa4w2FPOqSGybQzDBSAAx2bAWsjdP/wtHxISyI0JTsxCstjHYippkbvZsa4cDCn3a/7NQuIwrxwlzI3F5AVitENJcRBWDZlbbu1HKp3Af9MDRCj91nNlZrnJZ27CWzPiNhoW5wvo9a1I2+qUQoBvyKYxY0mPeBnSngaYTNXN8RU1MiTwQ6sri2TblSV8EXR+4org82NgjWdWM4L7Bsnz/bA2OTP7jMC1EePnAcsdvUwQPnbQtwIDAQAB" ;

        // 验签  ：去除sign和sign_type 参数 进行验签， checkV1 会在方法中去除，CheckV2不会去除sign_type，所以要手动排除
        boolean signVerified = AlipaySignature.rsaCheckV2(params, alipay_public_key, "utf-8", "RSA2"); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            // 订单id
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            if (StrUtil.isNotBlank(out_trade_no) && NumberUtil.isNumber(out_trade_no)) {
                Long orderId = Long.parseLong(out_trade_no);
                orderService.paySuccess(orderId, payType);
                log.info("支付成功");
            }
        } else {
            System.out.println("验签失败");
        }


    }
}
